package com.upc.feedish.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class DataBaseController {
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private String token;
    private String cookie;
    private String baseUrl="http://1.116.33.97:8080";
//  private String baseUrl="http://localhost:8080";


    public String getToken(){
        return this.token;
    }

    public int isLogin(String username,String password){
        URL url= null;
        String json="{\"username\":\""+username+"\",\"password\":\""+password+"\"}";

        try {
            url = new URL(baseUrl+"/login");
            OkHttpClient okHttpClient=new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            RequestBody requestBody=RequestBody.create(JSON,json);
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
            Call call =okHttpClient.newCall(request);
            Response response=call.execute();
            JSONObject resObject=new JSONObject((response.body().string()));
            int c=(Integer) resObject.get("code");
            if(c==100){
                JSONObject dataObj = (JSONObject) resObject.get("data");
                token=(String)dataObj.get("token");
            }
            return c;
        } catch (IOException e) {
            e.printStackTrace();
            return -500;
        }catch (JSONException e){
            e.printStackTrace();
            return -2;
        }
    }

    public int register(String username,String password,String cap){
        URL url= null;
        String json="{\"username\":\""+username+"\",\"password\":\""+password+"\"}";
        try {
            url = new URL(baseUrl+"/register?verCode="+cap);
            OkHttpClient okHttpClient=new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            RequestBody requestBody=RequestBody.create(JSON,json);
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .addHeader("Cookie",cookie)
                    .build();
            Call call =okHttpClient.newCall(request);
            Response response=call.execute();
            JSONObject resObject=new JSONObject((response.body().string()));
            int c=(Integer) resObject.get("code");
            if (c==100) return 1;
            else if(c==-1) return -1;
            else return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return -2;
        }catch (JSONException e){
            e.printStackTrace();
            return -3;
        }
    }

    public HashMap<String,Object> getAdvice(String token,String variety){
        HashMap<String,Object> resMap=new HashMap<>();
        URL url= null;
        String json="{\"variety\":\""+variety+"\"}";
        try {
            url = new URL(baseUrl+"/advice");
            OkHttpClient okHttpClient=new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            RequestBody requestBody=RequestBody.create(JSON,json);
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .addHeader("token",token)
                    .build();
            Call call =okHttpClient.newCall(request);
            Response response=call.execute();
            JSONObject resObject=new JSONObject((response.body().string()));
            JSONObject dataObj= (JSONObject) resObject.get("data");
            resMap.put("appetite",dataObj.get("appetite"));
            resMap.put("temperature",dataObj.get("temperature"));
            return resMap;

        }  catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return resMap;
    }

    public byte[] getFile(String token,String name){
        URL url= null;
        try {
            url = new URL(baseUrl + "/fileDownload?name="+name);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .addHeader("token",token)
                    .build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
            return  null;
    }

    public Bitmap getCap(){
        URL url= null;
        try {
            url = new URL( baseUrl+"/captcha");
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            Bitmap bitmap= BitmapFactory.decodeStream(response.body().byteStream());
            cookie=response.header("Set-Cookie");
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean isExpired(String token){
        URL url= null;
        try {
            url = new URL( baseUrl+"/outdated");
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(2, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("token",token)
                    .build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            JSONObject resObject=new JSONObject((response.body().string()));
            int code=(int)resObject.get("code");
            return code != 100;
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public int updateFile(String token ,byte[] bytes ,String name) {
        try {
            URL url = new URL(baseUrl + "/picUpload?name="+name);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5,TimeUnit.SECONDS)
                    .build();
            RequestBody rb=RequestBody.create(MediaType.parse("multipart/form-data"),bytes);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", name+"jpg", rb)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("token",token)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject=new JSONObject(response.body().string());
            jsonObject.get("code");
            return (int) jsonObject.get("code");
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }



    public Double[] getLocation(){
        Double[] o=new Double[3];
        URL url= null;
        try {
            url = new URL( baseUrl+"/location");
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(3, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            JSONObject resObject=new JSONObject((response.body().string()));
            JSONArray jsonArray= (JSONArray)resObject.get("data");
            for (int i=0;i<3;i++){
                o[i]= (Double) jsonArray.get(i);
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        return o;
    }
}

